// 图片预览功能（优化版）
const initUploader = () => {
    const fileInput = document.getElementById('fileInput');
    const imagePreview = document.getElementById('imagePreview');
    const dropZone = document.getElementById('dropZone');

    const handleFile = (file) => {
        if (!file) return;

        const reader = new FileReader();
        reader.onloadstart = () => {
            dropZone.style.backgroundColor = 'rgba(74, 144, 226, 0.05)';
        }
        reader.onload = (e) => {
            imagePreview.src = e.target.result;
            imagePreview.style.display = 'block';
            dropZone.style.backgroundColor = '';
            imagePreview.classList.add('animate__animated', 'animate__fadeIn');
        }
        reader.readAsDataURL(file);
    }

    fileInput.addEventListener('change', (e) => handleFile(e.target.files[0]));

    // 优化拖拽体验
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.style.transform = 'scale(1.02)';
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.style.transform = '';
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.style.transform = '';
        handleFile(e.dataTransfer.files[0]);
    });
}

// 初始化识别功能
const initAnalysis = () => {
    document.getElementById('runBtn')?.addEventListener('click', async function () {
        const btn = this;
        const panel = document.getElementById('analysisPanel');
        const resultArea = document.getElementById('analysisResult');

        btn.innerHTML = `<div class="spinner-border spinner-border-sm" role="status">
                               <span class="visually-hidden">Loading...</span>
                             </div> 正在识别...`;
        btn.disabled = true;

        try {
            const response = await fetch('/test', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({file_name: btn.value})
            });

            const data = await response.json();
            resultArea.innerHTML = `
                    <div class="alert alert-success animate__animated animate__fadeIn">
                        <h5><i class="bi bi-check-circle"></i> 识别成功！</h5>
                        <hr>
                        <p class="mb-0">${data.result}</p>
                    </div>
                `;
            panel.classList.add('visible');
        } catch (error) {
            resultArea.innerHTML = `
                    <div class="alert alert-danger animate__animated animate__shakeX">
                        <i class="bi bi-x-circle"></i> 识别失败：${error.message}
                    </div>
                `;
        } finally {
            btn.innerHTML = `<i class="bi bi-magic"></i> 重新识别`;
            btn.disabled = false;
        }
    });
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initUploader();
    initAnalysis();
});
